package com.yanqu.road.server.cmd.winery;


import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.winery.WineryProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.sync.message.SyncResponse;

import java.util.concurrent.CompletableFuture;


@Cmd(code = Protocol.S_WINERY_VISIT, desc = "拜访玩家酒坊")
public class WineryVisitCmd extends AbstractCommand {

    private WineryProto.WineryVisitReqMsg reqMsg;

    private WineryProto.WineryVisitRespMsg.Builder respMsgBuilder;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        this.reqMsg = WineryProto.WineryVisitReqMsg.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if (this.reqMsg.getVisitServerId() == GameServer.getInstance().getServerId()) {
            this.respMsgBuilder = UserMgr.wineryVisit(this.reqMsg.getVisitId());
        } else {
            this.respMsgBuilder = WineryProto.WineryVisitRespMsg.newBuilder();
            CompletableFuture<SyncResponse> responseFuture = GamePlayerMgr.sendToGameServer(this.reqMsg.getVisitServerId(), GameProtocol.S_SERVICE_WINERY_VISIT, player.getUserId(), this.reqMsg.toBuilder(), this.respMsgBuilder);
            responseFuture.thenAccept(syncResponse -> {
                if (syncResponse.getErrorCode() == 0) {
                    player.sendPacket(Protocol.U_WINERY_VISIT, this.respMsgBuilder);
                }
            });

//            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_WINERY_VISIT, this.reqMsg);
//            GamePlayerMgr.sendChannelPacket(player.getUserId(), pbMsg);

        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (this.reqMsg.getVisitServerId() == GameServer.getInstance().getServerId()) {
            player.sendPacket(Protocol.U_WINERY_VISIT, this.respMsgBuilder);
        }

    }

    @Override
    public boolean isDebug() {
        return true;
    }

    @Override
    public String getRequestData() {
        return this.reqMsg.toString();
    }
}
